package com.pansky.crm.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pansky.crm.common.mybatisplus.ApiResult;
import com.pansky.crm.common.mybatisplus.QueryWapperUtils;
import com.pansky.crm.common.mybatisplus.ResultPageDto;
import com.pansky.crm.common.mybatisplus.SuperServiceImpl;
import com.pansky.crm.entity.Department;
import com.pansky.crm.entity.Employee;
import com.pansky.crm.entity.UserLoginLog;
import com.pansky.crm.entity.bo.EmployeeBatchUpdateStatusDTO;
import com.pansky.crm.entity.bo.EmployeePageBo;
import com.pansky.crm.entity.bo.EmployeeUpdatePwdDTO;
import com.pansky.crm.entity.vo.EmployeeInfo;
import com.pansky.crm.entity.vo.EmployeeVo;
import com.pansky.crm.mapper.mysql.DepartmentMapper;
import com.pansky.crm.mapper.mysql.EmployeeMapper;
import com.pansky.crm.service.EmployeeService;
import com.pansky.crm.util.AES256Util;
import com.pansky.crm.util.BeanUtil;
import com.pansky.crm.util.TokenUtil;
import com.pansky.crm.util.VerificationUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author ：zhouzhiyong
 * @date ：Created in 2021/2/22 9:25
 * @description：员工服务
 */
@Service
@DS("mysqlDb")
@Slf4j
public class EmployeeServiceImpl extends SuperServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<EmployeeInfo> findEmployeeInfo(Employee employee) {
        return employeeMapper.queryEmployeeInfo(employee);
    }

    @Override
    public ResultPageDto queryByPage(EmployeePageBo employeePageBo) {
        IPage<Employee> page = new Page<>(employeePageBo.getPage(), employeePageBo.getLimit());
        QueryWrapper<Employee> queryWrapper = QueryWapperUtils.queryToWrapper(employeePageBo, Employee.class);
        IPage<Employee> dbResult = page(page, queryWrapper);
        //业务数据
        return defaultTransformPageData(dbResult,
                transform -> dbResult.getRecords().stream().map(employee -> {
                    EmployeeVo employeeVo = BeanUtil.copy(employee, EmployeeVo.class);
                    Department department = departmentMapper.selectById(employee.getDepartmentId());
                    employeeVo.setDepartmentName(department.getName());
                    return employeeVo;
                }).collect(Collectors.toList()));
    }

    @Override
    public Integer updateStatus(Integer employeeId, Integer status) {
        Employee employee = new Employee();
        employee.setId(employeeId);
        employee.setIsDisabled(status);
        return employeeMapper.updateById(employee);
    }

    @Override
    public boolean resetPasswd(Integer employeeId) {
        String defaultLoginPwd = AES256Util.encode(AES256Util.DEFAULT_SECRET_KEY, AES256Util.RESET_PASSWORD);
        log.info("--resetPasswd--defaultLoginPwd is {}", defaultLoginPwd);
        Employee employee = new Employee();
        employee.setId(employeeId);
        employee.setLoginPwd(defaultLoginPwd);
        int i = employeeMapper.updateById(employee);
        return i > 0;
    }

    @Override
    public boolean updatePwd(EmployeeUpdatePwdDTO updatePwdDTO, String token) {
        Claims tokenBody = TokenUtil.getTokenBody(token);
        String loginName = tokenBody.getSubject();
        if (StringUtils.isNotEmpty(loginName)) {
            QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("login_name", loginName);
            Employee employee = employeeMapper.selectOne(queryWrapper);
            if (Objects.equals(AES256Util.decode(AES256Util.DEFAULT_SECRET_KEY, employee.getLoginPwd()), updatePwdDTO.getOldPwd())) {
                employee.setLoginPwd(AES256Util.encode(AES256Util.DEFAULT_SECRET_KEY, updatePwdDTO.getPwd()));
                employeeMapper.updateById(employee);
                return true;
            } else {
                log.error("old pwd error.");
                return false;
            }
        } else {
            log.error("token sub name error.");
            return false;
        }

    }

    @Override
    public ApiResult<Boolean> addEmployee(Employee employee, String token) {
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(employee.getIdCard())) {
            boolean checkResult = Pattern.matches(VerificationUtil.ID_CARD, employee.getIdCard());
            if (!checkResult) {
                return ApiResult.failed("请输入正确的身份证号");
            }
        }
        if (null != employee.getBirthday()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formatBirthday = sdf.format(employee.getBirthday());
            boolean checkResult = Pattern.matches(VerificationUtil.DATE, formatBirthday);
            if (!checkResult) {
                return ApiResult.failed("生日格式不正确");
            }
        }
        //同名员工
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Employee::getLoginName, employee.getLoginName());
        List<Employee> sameNameEmployees = employeeMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(sameNameEmployees)) {
            return ApiResult.failed("登录名已存在!");
        }
        queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Employee::getPhone, employee.getPhone());
        //同电话员工
        List<Employee> samePhoneEmployees = employeeMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(samePhoneEmployees)) {
            return ApiResult.failed("手机号已经存在!");
        }
        //如果没有密码  默认设置为123456
        String pwd = employee.getLoginPwd();
        if (StringUtils.isEmpty(pwd)) {
            employee.setLoginPwd(AES256Util.encode(AES256Util.DEFAULT_SECRET_KEY, AES256Util.RESET_PASSWORD));
        } else {
            employee.setLoginPwd(AES256Util.encode(AES256Util.DEFAULT_SECRET_KEY, employee.getLoginPwd()));
        }
        employee.setCreateUser(Integer.valueOf(TokenUtil.getTokenBody(token).getId()));
        employeeMapper.insert(employee);
        return ApiResult.ok();
    }

    @Override
    public boolean updateBatchRoleId(List<Integer> employeeIdList, Integer roleId) {
        return employeeMapper.updateBatchRoleId(employeeIdList, roleId);
    }

    @Override
    public boolean batchUpdateStatus(EmployeeBatchUpdateStatusDTO batchUpdateStatusDTO) {

        employeeMapper.batchUpdateStatus(batchUpdateStatusDTO.getEmployeeIds(), batchUpdateStatusDTO.getStatus());
        return true;
    }
}
